package com.ylkj.common;

import org.apache.commons.lang.RandomStringUtils;

import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huyunfei 2015年8月24日 描述：生成主键
 */
public class GeneratorKey extends Thread{
	private static final long USER_STEP = 10;
	private static short USER_LAST_COUNT = 0;
	private static int USER_COUNT = 0;

	private static final long ONE_STEP = 10;
	private static final Lock LOCK = new ReentrantLock();
	private static long lastTime = System.currentTimeMillis();
	private static short lastCount = 0;
	private static int count = 0;

	/**
	 * 默认主键UUID 32位
	 * @return
	 */
	public static String genaraUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}
    /**
     * 生成6位随机数
     * @return
     */
    public static String genaraRand() {
        return RandomStringUtils.random(6, false, true);
    }

	/**
	 * 用户主键
	 * @return
	 */
	public static String genaraUserId() {

		LOCK.lock();
		try {
			if (USER_LAST_COUNT == USER_STEP) {
				boolean done = false;
				while (!done) {
					long now = System.currentTimeMillis();
					if (now == lastTime) {
						try {
							Thread.currentThread();
							Thread.sleep(1);
						} catch (InterruptedException e) {
						}
						continue;
					} else {
						lastTime = now;
                        USER_LAST_COUNT = 0;
						done = true;
					}
				}
			}
			USER_COUNT = USER_LAST_COUNT++;
		} finally {
			LOCK.unlock();
            return Long.toString(lastTime) + "" + String.format("%03d", USER_COUNT);
		}


	}


	@SuppressWarnings("finally")
	public static String genaraDefId() {
		LOCK.lock();
		try {
			if (lastCount == ONE_STEP) {
				boolean done = false;
				while (!done) {
					long now = System.currentTimeMillis();
					if (now == lastTime) {
						try {
							Thread.currentThread();
							Thread.sleep(1);
						} catch (InterruptedException e) {
						}
						continue;
					} else {
						lastTime = now;
						lastCount = 0;
						done = true;
					}
				}
			}
			count = lastCount++;
		} finally {
			LOCK.unlock();
            String s = Long.toString(lastTime);
			return s.substring(s.length()-12,s.length()) + "" + String.format("%03d", count);
		}
	}
	public void run(){
		for (int i = 0; i < 100; i++) {
			System.out.println("线程"+Thread.currentThread().getName()+":"+i+" = [" + GeneratorKey.genaraDefId() + "]");
		}
	}

	public static void main(String[] args) {
//		GeneratorKey t1 = new GeneratorKey();//创建线程
//		t1.start();//启动线程
//
//		//创建第二个线程
//		GeneratorKey t2 = new GeneratorKey();//创建线程
//		t2.start();//启动线程
//
//        //创建第二个线程
//        GeneratorKey t3 = new GeneratorKey();//创建线程
//        t3.start();//启动线程
//
//        //创建第二个线程
//        GeneratorKey t4 = new GeneratorKey();//创建线程
//        t4.start();//启动线程
//
//        //创建第二个线程
//        GeneratorKey t5 = new GeneratorKey();//创建线程
//        t5.start();//启动线程


        System.out.println(2.08*100);
    }

}
